import { Card, List } from "antd";
import _ from "lodash";
import React from "react";
import { useEditorContext } from "../../store/editor-provider";
import { WidgetInfo } from "../../types";
import CardContent from "../card-content";

type Props = {
  info: WidgetInfo;
};

function WidgetCard({ info }: Props) {
  const { editor, dispatch } = useEditorContext();
  const selectCard = editor?.curSelectedWidgetId;

  const isFollowGlobal = info.config?.card === "跟随全局";

  let finalCardStyle = isFollowGlobal
    ? editor.golbalSettings.cardStyle
    : _.merge(
        _.cloneDeep(editor.golbalSettings.cardStyle),
        info.config.cardStyle
      );

  const active = info.id === selectCard;

  const styles = active
    ? {
        style: {
          borderColor: "#3d7fe1"
        }
      }
    : {
        style: {
          borderColor: finalCardStyle.bgColor
        }
      };

  const handleSelect = (id: string) => {
    if (id !== editor.curSelectedWidgetId) {
      dispatch({ type: "select", payload: { id } });
    }
  };

  return (
    <List.Item>
      <Card
        bodyStyle={{
          background: finalCardStyle.bgColor,
          paddingTop: 0
        }}
        headStyle={{
          background: finalCardStyle.titleBgColor,
          color: finalCardStyle.titleColor,
          fontSize: finalCardStyle.titleSize
        }}
        title={info.config?.title || `${info.name} （${info.id}）`}
        hoverable
        onClick={() => handleSelect(info.id)}
        {...styles}
      >
        <CardContent info={info} />
      </Card>
    </List.Item>
  );
}

export default React.memo(WidgetCard);
